import React, { Component } from 'react';
import router from 'umi/router';
import styles from './index.less';
import { Toast } from 'antd-mobile';
import { fetchApi } from '@/utils/utils';

import {
  Player,
  ControlBar,
  PlayToggle, // PlayToggle 播放/暂停按钮 若需禁止加 disabled
  ReplayControl, // 后退按钮
  ForwardControl, // 前进按钮
  CurrentTimeDisplay,
  TimeDivider,
  BigPlayButton,
  PlaybackRateMenuButton, // 倍速播放选项
  VolumeMenuButton,
} from 'video-react';

class videoList extends Component {
  constructor(props) {
    super(props);
    this.play = this.play.bind(this);
    this.state = {
      id: '',
      videoInfo: {},
      userInfo: {},
      collectionStatus: false,
      otherHeight: '',
      currentSrc: '',
      currentTime: 0,
      duration: 1000,
      seekingTime: 0,
      buffered: {},
      waiting: false,
      seeking: false,
      paused: true,
      autoPaused: false,
      ended: false,
      playbackRate: 1,
      muted: false,
      volume: 1,
      readyState: 3,
      networkState: 2,
      videoWidth: 854,
      videoHeight: 480,
      hasStarted: true,
      userActivity: false,
      isActive: false,
      isFullscreen: false,
      activeTextTrack: null,
      error: null,
      src: '',
      srcObject: null,
      crossOrigin: null,
      //   preload: 'auto',
      defaultPlaybackRate: 1,
      played: {},
      seekable: {},
      autoplay: false,
      loop: false,
      controls: false,
      defaultMuted: false,
      textTracks: {},
      width: 0,
      height: 0,
      poster: '',
    };
  }
  async getCollectionStatus(id) {
    const phone = localStorage.getItem('phone');
    let res = await fetchApi(`web/collectionStatus?id=${id}&phone=${phone}`);
    if (res.status === 0) {
      if (res.data === 1) {
        this.setState({ collectionStatus: true });
      }
    }
  }

  async doCollectionVideo(id) {
    const phone = localStorage.getItem('phone');
    let res = await fetchApi(`web/doCollection?id=${id}&phone=${phone}`);
    if (res.status === 0) {
      Toast.success('收藏成功', 1);
      this.setState({
        collectionStatus: true,
      });
    }
  }
  async updateWatchNumber(id) {
    const phone = localStorage.getItem('phone');
    let res = await fetchApi(`web/watchUpdate?id=${id}&phone=${phone}`);
  }
  play() {
    this.player.play();
  }
  //   fullScreen() {
  //     let myVideo = document.querySelector('.video-react-video');
  //     console.log(myVideo);
  //     let w = document.documentElement.clientWidth || document.body.clientWidth;
  //     let h = document.documentElement.clientHeight || document.body.clientHeigth;
  //     let cha = Math.abs(h - w) / 2;
  //     myVideo.width = h;
  //     myVideo.height = w;
  //     myVideo.style.zIndex = 2000;
  //     myVideo.style.top = 0;
  //     myVideo.style.transform = 'translate(-' + cha + 'px,' + cha + 'px) rotate(180deg)';
  //   }
  async getUser() {
    const phone = localStorage.getItem('phone');
    let res = await fetchApi(`web/getUser?username=${phone}`);
    if (res.status === 0) {
      this.setState({
        userInfo: res.datas,
      });
    } else {
      Toast.fail('登陆信息失效，请重新登陆');
      router.push('/login');
    }
  }
  componentDidMount() {
    this.player.subscribeToStateChange(this.handleStateChange.bind(this));
    const { id } = this.props.history.location.query;
    this.setState({
      id,
    });
    this.getVideoInfo(id);
    this.getCollectionStatus(id);
    let video = document.querySelector('video');
    let videoStartBtn = document.querySelector('.video-react-big-play-button');
    videoStartBtn.addEventListener('click', e => {
      this.updateWatchNumber(id);
    });
    video.addEventListener('canplay', e => {
      this.setState({
        otherHeight: window.innerHeight - e.target.offsetHeight + 'px',
      });
    });
  }
  getVideoInfo = async id => {
    let res = await fetchApi(`web/videoInfo?id=${id}`);
    if (res.status === 0) {
      this.setState(
        {
          videoInfo: res.data,
          currentSrc: res.data.url,
        },
        () => {
          this.player.load();
          // this.player.subscribeToStateChange(this.handleStateChange.bind(this));
        }
      );
    }
  };
  collection = e => {
    const { collectionStatus } = this.state;
    if (!collectionStatus) {
      this.doCollectionVideo(this.state.id);
    }
  };
  handleStateChange(state, prevState) {
    this.setState({
      player: state,
    });
  }
  render() {
    const { videoInfo, currentSrc, collectionStatus, otherHeight } = this.state;
    return (
      <div>
        <Player
          ref={player => {
            this.player = player;
          }}
          poster={videoInfo.imgUrl}
        >
          <source src={currentSrc} />
          <BigPlayButton position="center" />
          <ControlBar autoHide={false} disableDefaultControls={false}>
            <ReplayControl seconds={10} order={1.1} />
            <ForwardControl seconds={30} order={1.2} />
            <PlayToggle />
            <CurrentTimeDisplay order={4.1} />
            <TimeDivider order={4.2} />
            <PlaybackRateMenuButton rates={[5, 2, 1.5, 1, 0.5]} order={7.1} />
            <VolumeMenuButton />
          </ControlBar>
        </Player>
        <div className="video-detail-wrap" style={{ height: otherHeight }}>
          <div className="video-detail-content">
            <div className="video-detail-title">
              <div className="video-title">{videoInfo.title}</div>
              <div className="video-people">
                <span className="iconfont icon-font-size">&#xe64b;</span>
                {videoInfo.playNumber || 0}次观看
              </div>
            </div>
            <div className="video-detail-desc">
              <div className="video-desc">简介</div>
              <div className="video-desc-text">{videoInfo.description}</div>
            </div>
            <div className="collection-video" onClick={this.collection}>
              {!collectionStatus ? (
                <span className="iconfont icon-font-size-large">&#xe573;</span>
              ) : (
                <span className="iconfont icon-font-size-large icon-font-color">&#xe607;</span>
              )}
              {!collectionStatus ? '收藏' : '已收藏'}
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default videoList;
